const app = getApp();

import request from "../../utils/request.js";
import local from "../../utils/local";
import nav from "../../utils/nav.js";
import toast from "../../utils/toast.js";

Page({
  data: {
    phoneCode: "",
    encryptedData: "",
    iv: "",
    username: '',
    nameFocus: false,

    appid: 'wx15a7538fa77ddfc0',
    i_my: '',
    i_zfmy: '',
    HostUrl: app.globalData.i_HostUrl,
    mch_id:  app.globalData.i_mch_id,
    jndiName: "",
    ok_url: "",
    openId: "",
    session_key: "",
    parentOpenId: "",
    sessionKey: "",
    js_code: "",
    backUrl: "",
    secret: "",
    headerUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
  },

  onLoad() {
    this.getPaipanmemberservice2()
  },

  getPaipanmemberservice2() {
    const that = this;
    let dic = {}
    const url = '/paipanmemberservice?appId='+ this.data.appid +'&eventCode=2'
    request.get(url,dic).then((res) => {
      console.log(res)
      const returnCode = res.RETURN
      if (returnCode == 1) {
        const object = res.APP_DB_INFO
        that.setData({
          jndiName: object.jndiName,
          secret: object.SECRET,
        })
      }
    })
  },

  getOpenId(code) {
    const that = this
    let dic = {
      'appId': this.data.appid,
      'js_code': code,
      'jndiName': this.data.jndiName,
      'grant_type': 'authorization_code',
      'eventCode': '111',
    }
    console.log(dic)
    let url = '/paipanmemberservice?appId='+ this.data.appid +'&js_code=' + code +'&jndiName=' + this.data.jndiName +'&grant_type=authorization_code&eventCode=111'
    request.get(url, {}).then((res) => {
      console.log(res)
      const returnCode = res.return
      if (returnCode == 1) {
        const tempOpenId = res.openid
        const tempSessionKey = res.session_key
        that.setData({
          openId: tempOpenId,
          session_key: tempSessionKey
        })
        if (tempOpenId.length != 0) {
          local.setLocal("openId", tempOpenId);
          that.getPaipanmemberservice1()
        }else{
          toast.showToast('获得信息异常，请重新进入小程序。')
        }
        
      }
    })
    
  },

  onClickToSelectHeaderUrl(e){
    var that =this
    wx.chooseMedia({
      sourceType: ['album', 'camera'],
      count: 1,
      mediaType: ['image',],
      maxDuration: 30,
      camera: 'back',
      success: function (res) {
        console.log(res["tempFiles"]);
        const tempDic = res["tempFiles"][0]
        const tempFilePath = tempDic["tempFilePath"]
        that.uploadHeaderImage(tempFilePath)
        
      },
      fail: function (err) {
       },
    });
  },

  getLoginCode() {
    var that = this
    wx.login({
      success: (res) => {
        console.log(res)
        const code = res.code
        that.setData({
          js_code: code
        })
        that.getOpenId(code)
      },
    })
  },

  getPhoneNumber(e) {
    console.log('======getPhoneNumber')
    console.log(e)
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
      toast.showToast('您已拒绝获取用户信息,将离开登录页')
      setTimeout(() => {
        nav.navigateBack("/index/index");
      }, 1500)
      return
    }
    let tempPhoneCode = e.detail.code || "";
    let tempEncryptedData = e.detail.encryptedData || "";
    let tempIv = e.detail.iv || "";
    this.setData({
      phoneCode: tempPhoneCode,
      encryptedData: tempEncryptedData,
      iv: tempIv,
    })
    this.getLoginCode()
  },

  handleLogin() {
    this.postMaintenanceLogin()
  },

  getPaipanmemberservice1() {
    const that = this;
    let dic = {}
    const url = '/paipanmemberservice?appId='+ this.data.appid + '&openId=' + this.data.openId +'&eventCode=1'
    request.get(url,dic).then((res) => {
      console.log(res)
      const returnCode = res.RETURN
      if (returnCode == 1) {
        const memInfo = res.MEM_INFO
        const memberID = memInfo.memberID
        const tel = memInfo.tel
        const memberName = memInfo.memberName
        if (memberID == 0) {
          that.getWxloginservlet()
        }else {
          console.log("==========================")
          local.setLocal("memberID", memberID);
          local.setLocal("tel", tel);
          local.setLocal("memberName", memberName);
          nav.navigateBack("/index/index");
        }
      }
    })
  },

  getWxloginservlet() {
    const that = this;
    let dic = {
      appid: this.data.appid,
      secret: this.data.i_my,
      encrypdata: this.data.encryptedData,
      ivdata: this.data.iv,
      sessionkey: this.data.session_key,
      jndiName: this.data.jndiName,
      eventCode: '2',
      nickName: '微信用户',
      gender: '0',
      avatarUrl: this.data.headerUrl,
      country: '',
      province: '',
      city: '',
      openId: this.data.openId,
      parentOpenId: '0'
    };
    console.log(dic)
    request.get("/wxloginservlet", dic).then(res => {
      console.log(res)
      const returnCode = res.RETURN
      if (returnCode == 1) {
        that.getPaipanmemberservice1()
      }
        
    });
  },


  postMaintenanceLogin() {
    console.log("============postMaintenanceLogin===========");
      let dic = {
        appid: this.data.appid,
        js_code: this.data.js_code,
        grant_type: 'authorization_code',
        wxUserInfo: 'intuit',
        jndiName: this.data.jndiName,
        eventCode: 1,
        openId: this.data.openId,
        secret: this.data.i_my,
        appkey: this.data.i_zfmy,
      };
      console.log(dic)
      request.get("/wxloginservlet", dic).then(res => {
    //     const code = res.code;
    //     const data = res && res.data || {}
    //     if (code == 200) {
    //       let idStr = JSON.stringify(data.id);
          // nav.switchTab("/index/index");
      });

  },

  uploadHeaderImage(filePath) {
    // url: HostUrl +'/wx/uploadpicserv', // 替换为实际的上传URL  
    //   filePath: avatarUrl, // 头像的临时文件路径  
    //   name: "pic", // 上传文件的参数名，可自定义  
    //   header: { // 请求头  
    //     'Content-Type': 'multipart/form-data',
    //     'jndiName': jndiName,
    //     'openId': openId, // 设置文件类型为多部分表单数据  
    //   },  
    request.uploadFile(
      "/wx/uploadpicserv", 
      filePath, 
      {
        file: filePath,
        name: "pic"
      }
      ).then(res => {
        console.log(res)
    });
  },


});
